package com.midea.leetcode;

import java.util.*;

/**
 * @description：
 * @author: wangwl23
 * @create: 2020-11-18 15:31
 */
public class LeetCode15 {
    public static void main(String[] args) {

        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> sum = threeSum(nums);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 3) return res;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) break;
            if (i > 0 && nums[i] == nums[i - 1]) continue; // 去重
            int start = i + 1;
            int ends = nums.length - 1;
            while (start < ends) {
                int sum = nums[i] + nums[start] + nums[ends];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[start], nums[ends]));
                    while (start < ends && nums[start] == nums[start + 1]) start++;
                    while (start < ends && nums[ends] == nums[ends - 1]) ends--;
                    start++;
                    ends--;
                } else if (sum > 0) ends--;
                else if (sum < 0) start++;

            }

        }
        return res;
    }
}
